package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
	"fmt"
	"github.com/kataras/go-errors"
	"luckapi/mutils"
)

type User struct {
	Id      	 int    `orm:"column(id);auto"`
	Avatar 	     string `orm:"column(avatar);size(200);null"`   //头像
	Name    	 string `orm:"column(name);size(200)"`          //用户姓名
	Balance  	 int    `orm:"column(balance)"`                 //账户余额
	UserId  	 string `orm:"column(userid);size(200);null"`   //用户ID
	Phone   	 string `orm:"column(phone);size(200);null"`
    Password 	 string `orm:"column(password);size(200);null"`
    Create_time  string `orm:"column(create_time);size(200);null"`
}

type Joiner struct {
	Id       	int    `orm:"column(id);auto"`
	Datetime	string `orm:"column(date_time);size(200)"`  //投注时间
	User     	*User  `orm:"rel(fk)"`	                //投注用户信息
	Game   	 	*Game  `orm:"rel(fk)"`					//投注的场次信息
	Luck_num	string `orm:"column(luck_number);size(200)"`             //投注后的分配的号码
}

/*
type Lucker struct {
	Id       int   	 `orm:"column(id);auto"`
	Datetime string	 `orm:"column(datetime);size(200)"` //开奖时间
	Money    int     `orm:"column(money)"`		        //中奖金额
	User     *User   `orm:"rel(one)"`                   //中奖用户信息
	Game   	 *Game 	 `orm:"rel(one)"`                   //中奖的场次信息
	Joiner 	 *Joiner `orm:"rel(one)"`                   //中奖的参与者信息
}
*/


func init() {
	// 需要在 init 中注册定义的 model
	orm.RegisterModel(new(User), new(Joiner))
}

func SqlDebug(bool bool)  {
	orm.Debug = bool
	//#自动建表
	orm.RunSyncdb("default", false, true)
}

func GetPersonByName(name string) (m map[string]string,apiError mutils.ApiError) {
	o := orm.NewOrm()
	var user User
	err := o.QueryTable("User").Filter("name",name).One(&user,"userid","phone","avatar","name","balance")
	m= make(map[string]string)
    m["userid"] = user.UserId
    m["phone"] = user.Phone
    m["avatar"] = user.Avatar
    m["name"] = user.Name
    m["balance"] = strconv.Itoa(user.Balance)
	if err != nil {
		apiError = mutils.ApiErrorWithErrorInfo(err,mutils.ErrorCode_User_Null)
	}
	return m,apiError
}


func GetPersonById(userId int) (m map[string]string,err error) {
	o := orm.NewOrm()
	var user User
	err = o.QueryTable("User").Filter("id",userId).One(&user,"userid","phone","avatar","name","balance")
	m= make(map[string]string)
	m["userid"] = user.UserId
	m["phone"] = user.Phone
	m["avatar"] = user.Avatar
	m["name"] = user.Name
	m["balance"] = strconv.Itoa(user.Balance)
	return m, err
}

func GetJoinerListByGameId (gameid int) (apiError mutils.ApiError,joiners []map[string]string){
	o := orm.NewOrm()
	var joinerlist []Joiner
	game := Game{Id:gameid}
	_, err := o.QueryTable("joiner").Filter("game",game).RelatedSel().All(&joinerlist)
	if err != nil {
		apiError = mutils.ApiErrorWithErrorInfo(err,mutils.ErrorCode_User_Null)
		return apiError,nil
	}
	joiners = make([] map[string]string, len(joinerlist))
	if len(joinerlist) > 0 {
		for i := 0; i <len(joinerlist); i++ {
			m := make(map[string]string)
			m["name"] = joinerlist[i].User.Name
			m["avatar"] = joinerlist[i].User.Avatar
			m["datetime"] = joinerlist[i].Datetime
			m["money"] = strconv.Itoa(joinerlist[i].Game.Join_gold)
			m["userid"] = joinerlist[i].User.UserId
			joiners[i] = m
		}
		apiError = mutils.SuccessApiError()
	}else {
		apiError = mutils.ApiErrorWithErrorInfo(err,mutils.ErrorCode_Game_NoJoiner)
	}
	return apiError,joiners
}

func GetJoinLuckNumByGameId(gameid int) (err error,joiners []int)  {
	_, err = orm.NewOrm().Raw("SELECT luck_number FROM joiner WHERE game_id = ?",gameid).QueryRows(&joiners)
	fmt.Println(joiners,err)
	if err != nil {
		return err,nil
	}

	return nil,joiners
}

func AddJoinerByUser(joiner Joiner) (err error) {
	_, err = orm.NewOrm().Insert(&joiner)
	return err
}

func UpdateUserGold(gold int, user User)  (err error) {
	o := orm.NewOrm()
	err1 := o.Read(&user)
	if err1 == nil {
		balance := user.Balance - gold
		if balance >= 0 {
			user.Balance = balance
			_, err = o.Update(&user,"balance")
		}else {
			err = errors.New("当前余额不足，请充值")
		}
		return err
	}
	return err1
}
//
//func AddNewPerson(user *User) (bool bool,message string) {
//	o := orm.NewOrm()
//	o.Using("default")
//	m, err1 := GetPersonByName(user.Name)
//	if err1 != nil{
//		//panic("mysql failed")
//		return false,"数据库操作失败!"
//	}
//	if m !=nil {
//		//panic("用户已经存在")
//		return false,"用户已经存在！"
//	}
//	_, err := o.Insert(user)
//	if err != nil {
//		return false,"用户注册失败！"
//	}
//	return true,"用户注册成功！"
//}

